package timestamp

import (
	"strconv"
	"time"

	"gitee.com/kobeyyf/apibox/handler"
)

func GetTimestampCheck(noBeforeSec, noAfterSec int64) handler.HandlerFunc {
	handleFunc := func(c *handler.Context) *handler.Response {
		reqTimestamp, err := strconv.ParseInt(c.Request.FormValue("Timestamp"), 10, 64)
		if err != nil {
			return handler.NewErrorResponseWith400(handler.ErrorCode_IllegalTimestamp, "Parse Timestamp Failed")
		}
		stime := time.Now().Unix()

		if stime > reqTimestamp {
			if (stime - noBeforeSec) < reqTimestamp {
				return nil
			}
		} else {
			if (stime + noAfterSec) > reqTimestamp {
				return nil
			}
		}
		return handler.NewErrorResponseWith400(handler.ErrorCode_IllegalTimestamp, "Timestamp error")
	}

	return handleFunc
}
